package com.tanhua.server.service;

import com.tanhua.autoconfig.template.FaceTemplate;
import com.tanhua.autoconfig.template.OssTemplate;
import com.tanhua.dubbo.api.UserInfoApi;
import com.tanhua.model.domain.UserInfo;

import com.tanhua.model.vo.ErrorResult;
import com.tanhua.model.vo.UserInfoVo;

import com.tanhua.server.exception.BusinessException;
import org.apache.dubbo.config.annotation.DubboReference;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@Service
public class UserInfoService {

    @DubboReference
    private UserInfoApi userInfoApi;
    @Autowired
    private OssTemplate ossTemplate;//阿里云
     @Autowired
    private FaceTemplate faceTemplate;//人脸识别模块

    public void save(UserInfo userInfo) {
        userInfoApi.save(userInfo);
    }

    /*更新用户头像*/
    public void updateHead(MultipartFile headPhoto, Long id) throws IOException {
        
        //1.将图片上传到阿里云
        String imageUrl = ossTemplate.upload(headPhoto.getOriginalFilename(), headPhoto.getInputStream());
        //2.进行人脸识别
        boolean detect = faceTemplate.detect(imageUrl);
        if (!detect){
            //没有人脸,抛出异常
           // throw new RuntimeException();
            throw new BusinessException(ErrorResult.faceError());
        }else {
            //有人脸的图片,更新对应的UserInfo信息
           UserInfo userInfo=new UserInfo();
           userInfo.setId(id);
           userInfo.setAvatar(imageUrl);
           userInfoApi.update(userInfo);
        }
    }

    public UserInfoVo findById(Long userID) {
      UserInfo userInfo =  userInfoApi.findById(userID);

      UserInfoVo vo=new UserInfoVo();
        BeanUtils.copyProperties(userInfo,vo);
        if(userInfo.getAge() != null) {
            vo.setAge(userInfo.getAge().toString());
        }

        return vo;
    }

    public void update(UserInfo userInfo) {
        //将要更新的数据传递给db层
        userInfoApi.update(userInfo);
    }



}
